-- **************************************************************************
-- * $Id: titancleaner.lua 5 2010-10-17 03:05:21Z bajtlamer $
-- **************************************************************************
-- * by Medyn @ Radek Roza / Czech Rep.
-- * Titan Clean is very simply World Of Warcraft AddOn, which help you to
-- * clean your bags for craps and all unwanted items or materials.
-- *
-- * Credits: Please post bug to bajt@volny.cz
-- *          look to www.rrsoft.cz/titan-gathered.html for new update and releases.
-- **************************************************************************

-- ******************************** Constants *******************************
local TitanClean_droppable = {};
local Color 	= {};

Color.green 	= "|cFF00FF00";
Color.yellow 	= "|cffffff20";
Color.red 		= "|cFFFF0000";
Color.blue 		= "|cFF0000FF";
Color.orange 	= "|cffff8020";
Color.grey 		= "|cffdddddd";
Color.default 	= "|r";

TitanCleaner 	= {}
-- Reduce the chance of functions and variables colliding with another addon.
local TC 		= TitanCleaner

TC.id 			= "Cleaner";
TC.addon 		= "Titan Cleaner";
TC.email 		= "bajtlamer@gmail.com";
TC.www 			= "www.rrsoft.cz";

--  Get data from the TOC file.
TC.version 		= tostring(GetAddOnMetadata("titancleaner", "Version")) or "Unknown"
TC.author 		= GetAddOnMetadata("titancleaner", "Author") or "Unknown"

-- Create about popup info text.
TC.about = TitanUtils_GetGreenText("Titan Panel [Cleaner]")..
	TitanUtils_GetHighlightText(" By ")..TitanUtils_GetNormalText(TC.author).."\n"..
	TitanUtils_GetNormalText("Version: ")..TitanUtils_GetHighlightText(TC.version).."\n"..
	TitanUtils_GetNormalText("email: ")..TitanUtils_GetHighlightText(TC.email).." - "..
	TitanUtils_GetHighlightText(TC.www);

function TC.Button_OnLoad(self)
	local tooltipAboutText;

    local function TitanPanelClean_AddItem(msg)
      local cmd,var = strsplit(' ', msg or "")
      if cmd then
        AddLootItem(cmd);
      else
        TitanPanelClean_PrintInfo();
      end
    end
    
    local function TitanPanelClean_DelItem(msg)
      local cmd,var = strsplit(' ', msg or "")
      if cmd then
        DeleteLootItem(cmd);
      else
        TitanPanelClean_PrintInfo();
      end
    end

    SlashCmdList["TCADD"] = TitanPanelClean_AddItem;
	SLASH_TCADD1 = "/tcadd"

    SlashCmdList["TCDEL"] = TitanPanelClean_DelItem;
	SLASH_TCDEL1 = "/tcdel"
	
    SlashCmdList["TCNUKE"] = nukeData;
	SLASH_TCNUKE1 = "/tcnuke"

    SlashCmdList["TCLIST"] = TitanPanelClean_ShowCleanDatabase;
	SLASH_TCLIST1 = "/tclist"

    SlashCmdList["TCREPAIR"] = TitanPanelClean_RepairDatabase;
	SLASH_TCREPAIR1 = "/tcrepair"
    
    SlashCmdList["TCHELP"] = PrintInfo;
	SLASH_TCHELP1 = "/tc"
	SLASH_TCHELP2 = "/tchelp"

	echo(Color.yellow..TC.addon.." ("..Color.green..TC.version..Color.yellow..") loaded! Created By "..TC.author);

	tooltipAboutText = "|cffff8020"..TC.addon.." "..TitanUtils_GetGreenText(TC.version).."\n";

	self.registry = {
		id 						= TC.id,
		version 					= TC.version,
		menuText 				= TC.id,
		buttonTextFunction	= "TitanPanelCleanButton_GetButtonText",
		tooltipTitle 			= tooltipAboutText,
		category 				= "Information",
		tooltipTextFunction 	= "TitanPanelCleanButton_GetTooltipText",
		icon 						= "Interface\\Addons\\TitanCleaner\\Artwork\\titancleaner",
		iconWidth 				= 16,
		updateType 				= TITAN_PANEL_UPDATE_TOOLTIP,
		savedVariables 		= {
			ShowIcon 			= 1,
			ShowLabelText 		= 1,
			ShowColoredText 	= 1,
			ShowBagJunk 		= 1,
			clearItems 			= {},
			lootedItems 		= {},
			deleteLog 			= {},
		}
	};
	
	self:RegisterEvent("PLAYER_ENTERING_WORLD");
	self:RegisterEvent("PLAYER_LEAVING_WORLD");
	self:RegisterEvent("LOOT_CLOSED");
end


--
-- Get tooltip text
--
function TitanPanelCleanButton_GetTooltipText()
	local tooltipText = "";
   	local nextText = "";
	local dbb = TitanGetVar(TC.id, "clearItems");

	if (dbb) then
		for i,e in pairs(dbb) do
			if (type(e) == "table") then
                if (e.name ~= nil) then
                    nextText = nextText..e.name..":\t"..e.value.."\n";
                end
			end
		end
	end
   tooltipText = tooltipText.."\n";
   tooltipText = tooltipText..TitanUtils_GetHighlightText(Color.orange.."Loot clean database:".."\n");
   tooltipText = tooltipText..nextText;
    	
    if ( not TitanGetVar(TC.id, "ShowBagJunk")) then
    	tooltipText = tooltipText.."\n";
    	tooltipText = tooltipText..TitanUtils_GetHighlightText(Color.orange.."Suggested Junk items in bag:".."\n");
    	tooltipText = tooltipText..TitanCleanGetItemsInBags();
    end
   	
	return tooltipText;
end


--
-- Get Bouton text
--
function TitanPanelCleanButton_GetButtonText()
	local txtTitanTitle = " ";

	return TC.addon, txtTitanTitle;

end


--
-- Register a Event
--
function TC.Button_OnEvent(event, arg1)

		if (event == "PLAYER_LEAVING_WORLD") then
		end
		if (event == "PLAYER_ENTERING_WORLD") then
		end
		if (event == "LOOT_CLOSED") then
			TitanPanelClean_onLootClosed();
		end

		TitanPanelButton_UpdateButton(TC.id);
end


--
-- Prepare main menu in Titan Panel
--
function TitanPanelRightClickMenu_PrepareCleanerMenu()
	local info;
	if ( UIDROPDOWNMENU_MENU_LEVEL == 2 ) then
	
 		if ( UIDROPDOWNMENU_MENU_VALUE == "DisplayAbout" ) then
			info = {};
			info.text = TC.about;
			info.value = "AboutTextPopUP";
			info.notClickable = 1;
			info.isTitle = 0;
			UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
		end

		return;
	end
		
	TitanPanelRightClickMenu_AddTitle(TitanPlugins[TC.id].menuText);

	TitanPanelRightClickMenu_AddToggleIcon(TC.id);
	TitanPanelRightClickMenu_AddToggleLabelText(TC.id);
 	TitanPanelRightClickMenu_AddCommand(TITAN_PANEL_MENU_HIDE, TC.id, TITAN_PANEL_MENU_FUNC_HIDE);

	-- info about plugin
	info = {};
	info.text = TITAN_CLEAN_ABOUT_TEXT;
	info.value = "DisplayAbout";
	info.hasArrow = 1;
	UIDropDownMenu_AddButton(info);
	
	-- Show Skills
	info = {};
	info.text = TITAN_CLEAN_LOCAL_SHOW_BAGJUNK;
	info.func = TitanPanelCleanButton_ToggleShowBagsJunk;
	info.checked = TitanUtils_Toggle(TitanGetVar(TC.id, "ShowBagJunk"));
	info.keepShownOnClick = 1;
	UIDropDownMenu_AddButton(info);

end


--
-- LIst all junks from database
--
function TitanPanelCleanButton_ToggleShowBagsJunk()
	TitanToggleVar(TC.id, "ShowBagJunk");
	TitanPanelButton_UpdateButton(TC.id);
end


--
-- VOID: Print message to default chat frame.
--
function echo(text)
	if (text) then
      DEFAULT_CHAT_FRAME:AddMessage(Color.red..text);
  end
end


--
-- VOID: cleaning script...
--
function TitanClear_onLoot()
	
	for index = 1, GetNumLootItems(), 1 do
		if (LootSlotIsItem(index)) then
	    	local texture, fishie, quantity, quality = GetLootSlotInfo(index);
	    	local link = GetLootSlotLink(index);
			local _,_, color, id, name = string.find(link, "|c(%x+)|Hitem:(%d+):[%d:]+|h%[(.-)%]|h|r");
			TitanPanelOre_updateHistory(name, quantity,link);
	 	end
	end
	
end


--
-- ADD item to junk database
--
function AddLootItem(ID)
	
	local db = TitanGetVar(TC.id, "clearItems");
	local i,d,v,r,found;
	local nitem = {};
    local sName, sLink, iRarity, iLevel, iMinLevel, sType, sSubType, iStackCount = GetItemInfo(ID);
	
    if(sName == nil) then
	   echo(ID.." not found!");
	   return;
	end

	found = 0;
	for i,d in pairs(db) do
		if (type(d) == "table")then
			if(d.id == ID)then
				r = d.value;
				found = i;
			end
		end
	end
	
	if(found > 0) then
	   echo(ID.." allready exist and deleted "..r.." time.");
	   return;
	else
        if (ID) then
    		nitem = { id = ID,name = sLink,value = 0};
    		table.insert(db,nitem);
    	    echo(TC.addon..":"..sLink.."("..Color.green..ID.."|r)".." has added to junk database.");
	    end
	end

	TitanSetVar(TC.id, "clearItems", db);
	
end


--
-- Remove item from junk database
--
function DeleteLootItem(ID)
	
	local db = TitanGetVar(TC.id, "clearItems");
	local i,d,v,r,found;

    local sName, sLink, iRarity, iLevel, iMinLevel, sType, sSubType, iStackCount = GetItemInfo(ID);
	
	found = 0;
	for i,d in pairs(db) do
		if (type(d) == "table")then
			if(d.id == ID)then
				found = i;
			end
		end
	end
	
	if(found > 0) then
   		table.remove(db,found);
   	    echo(Color.red..TC.addon.."|r: "..sLink.." ("..Color.green..ID.."|r) has removed from junk database.");
	else
	    echo(TC.addon..":"..Color.red.."No Items found in junk database!");
	end

	TitanSetVar(TC.id, "clearItems", db);
	
end


--
-- Show info on game tooltip
--
function TitanPanelClean_ShowTooltip(item)
 	local lbl = getglobal("GameTooltipTextLeft1");
    local itemName = lbl:GetText();
    local strJunk = "";

    local sName, sLink, iRarity, iLevel, iMinLevel, sType, sSubType, iStackCount = GetItemInfo(itemName);
    
    local isRegistered = TitanPanelClean_IsRegistered(sName);
    if (isRegistered > 0) then
        strJunk = Color.red.." Junk|r";
    end
    if (sLink) then
	   local found, _, itemString = string.find(sLink, "^|c%x+|H(.+)|h%[.*%]");
    
	    if (itemString) then
    		GameTooltip:AddLine("|r"..itemString..strJunk, 0, 50, 255);
	    end
	end
        
	GameTooltip:Show();
end


--
-- Clean the database..
--
function TitanPanelClean_ShowCleanDatabase()
	local dbb = TitanGetVar(TC.id, "clearItems");
	local i,e;
	local found = 0;

	echo(Color.yellow.." ");
	echo(Color.yellow..TC.addon.." junk database preview:");
	echo(Color.yellow.."------------------------------------------------");

	if (dbb) then
		for i,e in pairs(dbb) do
			if (type(e) == "table") then
			     if (e.name ~= nil) then
				    echo(e.name..Color.green.." ("..e.id..") "..Color.orange..e.value.."|rx");
				    found = found + 1;
				else
				    echo(Color.yellow.."!Some data in Junk database could be corupted! |r/tcrepair "..Color.yellow.."should fix the problem.|r");
				    return;
				end
			end
		end
	end
    
	echo(Color.yellow.."------------------------------------------------");
   echo(Color.green..found.."|r items found in junk database.");
end


--
-- Repair database
--
function TitanPanelClean_RepairDatabase()
	local dbb = TitanGetVar(TC.id, "clearItems");
	local i,e;
    local found = 0;

	if (dbb) then
		for i,e in pairs(dbb) do
			if (type(e) == "table") then
			     if (e.name == nil) then
			   		table.remove(dbb,i);
			   		found = found  + 1;
				end
			end
		end
	end
    
    if (found > 0) then
        echo(Color.red.."Found "..found.." error(s). Database fixed.|r");
    else
        echo(Color.red.."NO Errors found.|r");
    end
    
	TitanSetVar(TC.id, "clearItems", dbb);

end


--
-- Show loot database
--
function TitanPanelClean_ShowLootDatabase()
	local dbloot = TitanGetVar(TC.id, "lootItems");
	local i,e;

	echo(Color.yellow.." ");
	echo(Color.yellow..TC.addon.." loot items database:");
	echo(Color.yellow.."------------------------------------------------");

	if (dbloot) then
		for i,e in pairs(dbloot) do
			if (type(e) == "table") then
				echo(e.name..Color.green.." "..Color.red..e.value.."|rx");
			end
		end
	end

	echo(Color.yellow.."------------------------------------------------");
end


--
-- EVENT: on loot closed
--
function TitanPanelClean_onLootClosed()
	
	local dbc = TitanGetVar(TC.id, "clearItems");
	local i,e;
	local deleted = 0;
	
	if (dbc) then
		for i,e in pairs(dbc) do
    
			deleted = DestroyIteminBags(e.id);
			
			if (deleted > 0) then
         	newValue = e.value + deleted;
            nitem = { id = e.id,name = e.name,value = newValue};
            table.remove(dbc, i);
		      table.insert(dbc, i, nitem);
			end
		end
	end
end


--
-- Check for registered item
--
function TitanPanelClean_IsRegistered(itemName)
	local db = TitanGetVar(TC.id, "clearItems");
	local i,d;
	
	for i,d in pairs(db) do
		if (type(d) == "table")then
		    
            local dName = GetItemInfo(d.name);
            
            if (dName ~= nil) then
    			if(dName == itemName)then
    				return i;
    			end
    		end
		end
	end
	
	return 0;
end


--
-- VOID: destroy item in bag
--
function DestroyIteminBags(itemID)
	local nbslots, b, s, t, n;
	local i_count = 0;
	local nitem = {};
	local curTime = date("%d.%m.%y %H:%M:%S");
	local dbd = TitanGetVar(TC.id, "deleteLog");
		
		for b=0,4 do
			nbslots=GetContainerNumSlots(b);
			for s=0,nbslots do
			local texture, itemCount = GetContainerItemInfo(b, s);

			t = GetContainerItemLink(b, s);

			if (t and itemID ~= nil) then
           	local _,_, color, bagID, name = string.find(t, "|c(%x+)|Hitem:(%d+):[%d:]+|h%[(.-)%]|h|r");
            local sName, sLink, iRarity, iLevel, iMinLevel, sType, sSubType, iStackCount = GetItemInfo(t);
            local xName = GetItemInfo(itemID);

					if (sName == xName and iRarity < 2) then
						i_count = i_count + itemCount;
                  PickupContainerItem(b,s);

                  if ( CursorHasItem() ) then
                     DeleteCursorItem();
            			PlaySound("TellMessage");
          				echo(Color.red..">>Deleted "..t.." "..itemCount.."x |r");
          		      nitem = { time = curTime,name = t,value = itemCount};
                    	table.insert(dbd,nitem);
                  end
					end
				end
			end
		end
		
	return i_count;
end


--
-- VIOD: Nukke data from database
--
function nukeData()
	local dbc = TitanGetVar(TC.id, "clearItems");
	local nitem = {};
    TitanSetVar(TC.id, "clearItems", nitem);
    echo("Titan Clean: Database cleared.");
end


--
-- Format a money
--
function TitanClean_GetGSC(money)
	if (money == nil) then return 0, 0, 0 end
	local g = math.floor(money / 10000);
	local s = math.floor((money - (g*10000)) / 100);
	local c = math.floor(money - (g*10000) - (s*100));
	return g,s,c;
end


--
-- Convert price to string
--
function TitanClean_GetPriceAsText(money)
	if (money == nil) then return 0, 0, 0 end
	local str = "";
	
	local g = math.floor(money / 10000);
	local s = math.floor((money - (g*10000)) / 100);
	local c = math.floor(money - (g*10000) - (s*100));
	
	if (g > 0) then
	   str = str..TC_GOLD..g..".|r";
	end
	if (s > 0) then
	   str = str..TC_SILVER..s..".|r";
	end
	if (c > 0) then
	   str = str..TC_COPPER..c.."|r";
	end
	
	return str;
end

--
-- Retrn a sell valu from item
--
function GetSellValue(item)
	local id = type(item) == "number" and item or type(item) == "string" and tonumber(item:match("item:(%d+)"))

	if not id and type(item) == "string" then -- Convert item name to itemid, only works if the player has the item in his bags
		local _, link = GetItemInfo(item)
		id = link and tonumber(link:match("item:(%d+)")) 
	end

	return id and ((id) or origGetSellValue and origGetSellValue(id))
end

--
-- Get item from bag
--
function TitanCleanGetItemsInBags(item)
	local nbslots, b, s, t, n;
	local tooltip = "";
			
	for b=0,4 do
		local nbslots = GetContainerNumSlots(b);
		
		for s=0,nbslots do

			t = GetContainerItemLink(b, s);
		   local texture, itemCount = GetContainerItemInfo(b, s);

			if (t ~= nil) then
            local origGetSellValue = GetSellValue(t)
            local sName, sLink, iRarity, iLevel, iMinLevel, sType, sSubType, iStackCount = GetItemInfo(t);
          	local found, _, itemID = string.find(sLink, "item:(%d+)");
          	
				if (sName and origGetSellValue and itemID) then
					local price = TitanClean_GetPriceAsText(origGetSellValue);
					local g,s,c = TitanClean_GetGSC(origGetSellValue);
               local _, _, locked = GetContainerItemInfo(b, s)
               local isDropable = TitanClear_IsDroppable(sType,sSubType);
          		if (not locked and isDropable and iRarity < 2) then
                  tooltip = tooltip..itemID.." "..t..":\t"..price.." "..itemCount.."x".."\n";
               end
				end
			end
		end
	end
	
	return tooltip;
end


--
-- Chesk if item is dropable
--
function TitanClear_IsDroppable(type,subtype)

	if (not type or not subtype) then return false end
	if (subtype == "Miscellaneous" or type == "Miscellaneous") then return false end
	if (subtype == "Fishing Poles") then return false end
	if (subtype == "Elixir") then return false end
	if (subtype == "Potion") then return false end
	
	if (type == "Quest") then return false end
	if (type == "Recipe") then return false end
	if (type == "Container") then return false end
	if (type == "Gem") then return false end
	if (type == "Key") then return false end
	if (type == "Projectile") then return false end
	if (type == "Quiver") then return false end
	if (type == "Reagent") then return false end
	if (type == "Trade Goods") then return false end
	return true
end


--
-- VOID: Print info
--
function PrintInfo()

	echo(Color.yellow.." ");
	echo(Color.yellow.."------------------------------------------------");
	echo(Color.yellow..TC.addon.." avaliable commands:");
	echo(Color.yellow.."------------------------------------------------");

	echo("- tchelp - "..Color.yellow.."print this help.");
	echo("- tcadd {item ID} - "..Color.yellow.."add item to junk database.");
	echo("- tcdel {item ID} - "..Color.yellow.."remove item from junk database.");
	echo("- tclist - "..Color.yellow.."list all items allready added to junk database.");
	echo("- tcrepair - "..Color.yellow.."try to repair corrupted junk database.");
	echo(" ");
end
